import 'package:api/api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:video_player/player.dart';

import '../../../components/future_builder_handler.dart';
import '../../../components/no_data.dart';
import '../../../l10n/app_localizations.dart';
import '../../../providers/user_config.dart';
import '../../../validators/validators.dart';
import '../../utils/notification.dart';
import '../../utils/utils.dart';

class SubtitleManager extends StatefulWidget {
  const SubtitleManager({super.key, required this.fileId});

  final String fileId;

  @override
  State<SubtitleManager> createState() => _SubtitleManagerState();
}

class _SubtitleManagerState extends State<SubtitleManager> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(AppLocalizations.of(context)!.buttonSubtitle),
        actions: [
          IconButton(
            onPressed: () async {
              final subtitle = await showDialog<SubtitleData>(
                context: context,
                builder: (context) => const SubtitleDialog(),
              );
              if (subtitle != null && context.mounted) {
                final resp = await showNotification(context, Api.subtitleInsert(widget.fileId, subtitle));
                if (resp?.error == null && context.mounted) setState(() {});
              }
            },
            icon: const Icon(Icons.add),
          ),
        ],
      ),
      body: LayoutBuilder(
        builder: (context, constraints) {
          return FutureBuilderHandler(
            future: Api.subtitleQueryById(widget.fileId),
            builder:
                (context, snapshot) =>
                    snapshot.requireData.isNotEmpty
                        ? ListView.builder(
                          itemCount: snapshot.requireData.length,
                          itemBuilder: (context, index) {
                            final item = snapshot.requireData[index];
                            return Slidable(
                              endActionPane: ActionPane(
                                extentRatio: 48 / constraints.maxWidth,
                                motion: const BehindMotion(),
                                children: [
                                  IconButton(
                                    onPressed: () async {
                                      final confirm = await showConfirm(
                                        context,
                                        AppLocalizations.of(context)!.deleteConfirmText,
                                      );
                                      if (confirm != true || !context.mounted) return;
                                      final resp = await showNotification(context, Api.subtitleDeleteById(item.id));
                                      if (resp?.error == null && context.mounted) setState(() {});
                                    },
                                    icon: const Icon(Icons.delete_outline_rounded),
                                  ),
                                ],
                              ),
                              child: ListTile(
                                leading: Text(item.mimeType ?? ''),
                                trailing: Text(item.language ?? ''),
                                title: Text(item.label ?? ''),
                              ),
                            );
                          },
                        )
                        : const NoData(),
          );
        },
      ),
    );
  }
}

class SubtitleDialog extends StatefulWidget {
  const SubtitleDialog({super.key, this.subtitle});

  final SubtitleData? subtitle;

  @override
  State<SubtitleDialog> createState() => _SubtitleDialogState();
}

class _SubtitleDialogState extends State<SubtitleDialog> {
  final _controller = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  String? _mimeType;
  String? _language;
  String? _filename;
  bool selected = false;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(AppLocalizations.of(context)!.buttonSubtitle),
      scrollable: true,
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          spacing: 12,
          children: [
            TextFormField(
              autofocus: true,
              controller: _controller,
              decoration: InputDecoration(
                prefixIcon: const Icon(Icons.link),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.folder_open_rounded),
                  onPressed: () async {
                    final res = await showDriverFilePicker(
                      context,
                      AppLocalizations.of(context)!.titleEditSubtitle,
                      selectableType: FileType.file,
                    );
                    if (res != null) {
                      final file = res.$2;
                      final ar = file.name.split('.');
                      final ext = ar.lastOrNull;
                      _mimeType = SubtitleMimeType.fromString(ext)?.name;
                      _filename = ar.firstOrNull;
                      _controller.text = 'driver://${res.$1}/${file.id}';
                      setState(() {});
                    }
                  },
                ),
                hintText: widget.subtitle?.label?.toString(),
                filled: true,
                isDense: true,
                labelText: AppLocalizations.of(context)!.subtitleFormItemLabelUrl,
              ),
              validator: (value) => requiredValidator(context, value),
              onChanged: (value) {
                if (value.startsWith(RegExp(r'^http(s)://'))) {
                  final uri = Uri.parse(value.trim());
                  final filename = uri.path.split('/').lastOrNull;
                  final ar = filename?.split('.');
                  final ext = ar?.lastOrNull;
                  _filename = ar?.firstOrNull;
                  _mimeType = SubtitleMimeType.fromString(ext)?.name;
                  setState(() {});
                }
              },
            ),
            DropdownButtonFormField(
              value: _mimeType,
              decoration: InputDecoration(
                prefixIcon: const Icon(Icons.subtitles_outlined),
                filled: true,
                isDense: true,
                labelText: AppLocalizations.of(context)!.subtitleFormItemLabelType,
              ),
              items: [
                DropdownMenuItem(
                  child: Text(
                    AppLocalizations.of(context)!.formItemNotSelectedHint,
                    style: Theme.of(context).textTheme.labelSmall,
                  ),
                ),
                ...SubtitleMimeType.values.map(
                  (mime) => DropdownMenuItem(value: mime.name, child: Text(mime.name.toUpperCase())),
                ),
              ],
              validator: (value) => requiredValidator(context, value),
              onChanged: (v) => setState(() => _mimeType = v),
            ),
            DropdownButtonFormField(
              value: _language,
              decoration: InputDecoration(
                prefixIcon: const Icon(Icons.language),
                filled: true,
                isDense: true,
                labelText: AppLocalizations.of(context)!.subtitleFormItemLabelLanguage,
              ),
              items: [
                DropdownMenuItem(
                  child: Text(
                    AppLocalizations.of(context)!.formItemNotSelectedHint,
                    style: Theme.of(context).textTheme.labelSmall,
                  ),
                ),
                ...SystemLanguage.values.map(
                  (lang) => DropdownMenuItem(value: lang.name, child: Text(lang.name.toUpperCase())),
                ),
              ],
              onChanged: (v) => setState(() => _language = v),
            ),
            CheckboxListTile(
              dense: true,
              title: Text(AppLocalizations.of(context)!.formLabelSelectedByDefault),
              contentPadding: const EdgeInsets.only(left: 8),
              value: selected,
              onChanged: (v) => setState(() => selected = v ?? false),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        FilledButton(
          onPressed: () {
            if (_formKey.currentState!.validate() && _mimeType != null) {
              Navigator.of(context).pop(
                SubtitleData(
                  url: _controller.text,
                  mimeType: _mimeType,
                  language: _language,
                  label: _filename,
                  selected: selected,
                ),
              );
            }
          },
          child: Text(AppLocalizations.of(context)!.buttonConfirm),
        ),
        TextButton(onPressed: () => Navigator.pop(context), child: Text(AppLocalizations.of(context)!.buttonCancel)),
      ],
    );
  }
}
